# 判断用户是否登录, 如果登录, 正常调用, 如果没有登录, 返回json
from django import http

from users.models import User
from utils.response_code import RET


def login_required_json(view_func):
    def wrapper(request, *args, **kwargs):
        if request.user.is_authenticated:
            return view_func(request, *args, **kwargs)

        else:

            return http.JsonResponse({"errno": RET.SESSIONERR, "errmsg": "未登录"})

    return wrapper


class LoginRequiredJsonMixin(object):

    @classmethod
    def as_view(cls, *args, **kwargs):
        view = super().as_view(*args, **kwargs)
        return login_required_json(view)


def login_real_name(view_func):
    def wrapper(request, *args, **kwargs):
        # if User.objects.filter(id_card=request.user.id_card):
        #     return view_func(request, *args, **kwargs)
        # else:
        #     return http.JsonResponse({'code': RET.SESSIONERR,
        #                               'errmsg': '不是房东'})
        user = User.objects.get(id=request.user.id)
        real_name = user.real_name
        id_card = user.id_card
        if real_name is not None and id_card is not None:
            return view_func(request, *args, **kwargs)
        else:
            return http.JsonResponse({'code': RET.SESSIONERR,
                                      'errmsg': '不是房东'})

    return wrapper


class Whetherowner(LoginRequiredJsonMixin):

    @classmethod
    def as_view(cls, *args, **kwargs):
        view = super().as_view(*args, **kwargs)
        return login_real_name(view)
